// pages/trading/prepare/parepare.js

import Router from "../../../class/Router";
import MallService from "../../../class/service/MallService";
import AddressService from "../../../class/service/AddressService";
import SmsService from "../../../class/service/SmsService";
import OrderService from "../../../class/service/OrderService";
import ShoppingService from "../../../class/service/ShoppingService";
import Tips from "../../../utils/Tips";

const mallService = new MallService();
const addressService = new AddressService();
const smsService = new SmsService();
const orderService = new OrderService();
const shoppingService = new ShoppingService();
const util = require("../../../utils/util.js")
const storage = require("../../../utils/storage.js")
const constant = require("../../../constant.js")
const notification = require("../../../utils/WxNotificationCenter.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    codeMsg: '获取验证码'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      id: options.id,
      courseIds: options.courses
    })
    var unionid = wx.getStorageSync(storage.keys.unionid);
    that.setData({
      unionid: unionid
    })

    var openid = wx.getStorageSync(storage.keys.openid);
    that.setData({
      openid: openid
    })

    var mobile = wx.getStorageSync(storage.keys.mobile);
    that.setData({
      mobile: mobile
    })

    that.changeSubmitStatus();

    notification.addNotification("ON_ADDRESS_CHOICE", that.updateAddress, that);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;

    Tips.loading();

    mallService.detail(that.data.id).then(data => {
      // Tips.loaded();
      that.setData({
        "init": true,
        "sku": data.sku,
        "courses": data.courses
      })
      that.initProducts();

      if (!that.data.selectAddress) {
        addressService.getDefault(that.data.unionid).then(data => {
          Tips.loaded();
          that.initDefaultAddres(data.userAddresse)
        }, res => {
          Tips.error("获取用户地址失败");
          that.setData({
            "init": true
          })
        })
      } else {
        Tips.loaded();
        that.setData({
          "init": true
        })
      }

      that.changeSubmitStatus();

    }, res => {
      Tips.error("获取商品详情失败");
      that.setData({
        "init": true
      })
    })
  },

  initProducts: function() {
    var that = this;
    var totalPrice = 0;
    var product = {};
    var productName = that.data.sku.name;
    product["productId"] = that.data.sku.id;
    product["productName"] = productName;
    let courseIdString = ',' + that.data.courseIds + ',';
    let selectedCourses = [];
    for(var i in that.data.courses) {
      if (courseIdString.indexOf(',' + that.data.courses[i].id + ',') != -1) {
        selectedCourses.push(that.data.courses[i])
        totalPrice = totalPrice + that.data.courses[i].price
      }
    }
    product["courses"] = selectedCourses;
    that.setData({
      product: product,
      totalPrice: totalPrice
    })
  },

  initDefaultAddres: function(defaultAddress) {
    var that = this;
    var address = {};
    address['id'] = defaultAddress.id;
    address['name'] = defaultAddress.reciver;
    address['phone'] = defaultAddress.reciver_mobile;
    address['fullAddress'] = defaultAddress.province + defaultAddress.city + defaultAddress.district + defaultAddress.address;

    that.setData({
      address: address
    })

    that.changeSubmitStatus();
  },

  updateAddress: function(address) {

    if (this.data.address != null) {
      const oldAddressId = this.data.address.id;
      if (address.id == oldAddressId) {
        return;
      }
    }

    if (address) {
      this.setData({
        selectAddress: address,
        address: address
      });

      this.changeSubmitStatus();
    }
  },

  changeSubmitStatus: function() {
    var that = this;
    if(that.data.mobile && that.data.address) {
      that.setData({couldBuy: true})
    }
  },

  prepay: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 切换地址
   */
  onAddressTap: function(event) {

    var that = this;

    if (that.data.mobile) {
      Router.addressIndex('choice', that.data.address.id);
    } else {
      that.showMessage("请先绑定手机")
    }
  },

  showMessage: function(text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function() {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },

  /**
   * 下单
   */
  onConfirmTap: function(event) {
    var that = this;

    if (that.data.couldBuy) {
      Tips.loading("正在创建订单")
      orderService.create(that.data.unionid, that.data.address.id, that.data.sku.id, that.data.courseIds).then(data => {
        Tips.loaded();
        that.setData({
          order: data.order
        })
        Tips.loading("正在生成支付请求")
        shoppingService.prepare(data.order.id, that.data.unionid).then(data => {
          console.log(data);
          Tips.loaded();
          var payConfig = data.payConfig;
          wx.requestPayment({
            'timeStamp': payConfig.timestamp,
            'nonceStr': payConfig.nonceStr,
            'package': payConfig.package,
            'signType': 'MD5',
            'paySign': payConfig.paySign,
            'success': function (res) {
              console.log(res);
              wx.redirectTo({
                url: '../../../pages/trading/result/result?order=' + that.data.order.code
              })
            },
            'fail': function (res) {
              Tips.error("支付失败")
            }
          })

        }, res => {
          Tips.error("生成支付请求失败")
        })

      }, res=> {
        Tips.error("订单创建失败");
      })
    }
  },

  onInputPhone: function(e) {
    var that = this;
    that.setData({
      phone: e.detail
    })
  },

  inputCode: function (e) {
    var that = this;
    that.setData({
      code: e.detail
    })
    if(that.data.code.length == 6) {
      that.bindUser();
    }
  },

  bindUser: function() {
    var that = this;
    smsService.bindUser(that.data.unionid, that.data.phone, that.data.code, that.data.token, that.data.openid).then(data => {
      that.setData({
        mobile: data.user.mobile
      })
      wx.setStorageSync(storage.keys.mobile, that.data.mobile)
    }, res => {
      Tips.error("绑定验证码失败");
      that.setData({
        disableGetCode: false,
        codeMsg: "获取验证码"
      })
    })
  },

  validMobile: function() {
    var that = this;
    if (!that.data.phone) {
      that.showMessage("请先输入手机")
      return false;
    } else if (!/^((13)|(14)|(15)|(16)|(17)|(18)|(19))\d{9}$/.test(that.data.phone)) {
      that.showMessage("请输入正确的手机")
      return false;
    }

    return true;
  },

  onSendSms: function(event) {

    var that = this;
    if (that.validMobile()) {

      that.setData({
        disableGetCode: true
      })

      var seconds = 60;
      var interval = setInterval(function(e) {
        seconds--;
        if (seconds < 0) {
          that.setData({
            disableGetCode: false,
            codeMsg: "重新获取验证码"
          })
          clearInterval(interval);
        } else {
          that.setData({
            codeMsg: "发送中（" + seconds + "）秒"
          })
        }
      }, 1000)

      smsService.send(that.data.phone).then(data => {
        that.setData({
          token: data.token
        })
        Tips.loaded();
      }, res => {
        Tips.error("获取验证码失败");
        that.setData({
          disableGetCode: false,
          codeMsg: "获取验证码"
        })
        clearInterval(interval);
      });
    }
  }
})